package com.common.base.utils

import android.content.Context
import android.graphics.Bitmap
import id.zelory.compressor.Compressor
import id.zelory.compressor.constraint.destination
import id.zelory.compressor.constraint.format
import id.zelory.compressor.constraint.quality
import id.zelory.compressor.constraint.resolution
import id.zelory.compressor.constraint.size
import java.io.File
import java.io.IOException

/**
 * 图片压缩工具类
 */
object CompressorHelper {

    @Throws(IOException::class)
    suspend fun compressorPicture(context: Context?, file: File): File {
        return compressorFactory(context, file)
    }

    @Throws(IOException::class)
    suspend fun compressorAvatar(context: Context, file: File): File {
        return compressorFactory(context, file)
    }

    @Throws(IOException::class)
    private suspend fun compressorFactory(context: Context?, file: File): File {
        if(context == null){
            //处理context为空的情况 解决空指针问题
            return file
        }
        val uri = FileProvider7.getPhotoUri()
        val path = RealPathFromUriUtils.getFilePathFromURI(context, uri!!)
//        return Compressor(context)
//            .setQuality(80)
//            .setDestinationDirectoryPath(path)
//            .compressToFile(file)

        return Compressor.compress(context, file) {
            resolution(1280, 720)
            quality(80)
//            destination(file)
//            format(Bitmap.CompressFormat.PNG)
            size(2_097_152) // 2 MB
        }
    }

    private fun isValidExtensionName(extension: String): Boolean {
        return extension.equals("jpg", ignoreCase = true) || extension.equals("jpeg", ignoreCase = true) || extension.equals("png", ignoreCase = true)
    }
}
